import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import java.io.*;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class PoiUtil {


    public static ResultModel calculate(File file) {
        try {
            Sheet sheet = null;
            Row row = null;
            Row rowHeader = null;
            if (file == null) {
                return null;
            }

            DataInputStream in = new DataInputStream(new FileInputStream(file));
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "Unicode"));
            reader.readLine();
            String line = null;
            double coin = 0L;
            double sumPrise = 0L;
            double avg = 0L;
            while ((line = reader.readLine()) != null) {
                String item[] = line.split("\t");
                if (item.length != 0 && item.length >= 6) {
                    Pattern p = Pattern.compile("([0-9]{1,}[.][0-9]*)");
                    Matcher m_price = p.matcher(item[6]);
                    Matcher m_count = p.matcher(item[5]);
                    if (!m_price.find()) {
                        System.out.println(item[6]);
                    }
                    if (!m_count.find()) {
                        System.out.println(item[5]);
                    }
                    if ("买入".equals(item[2])) {

                        sumPrise += Double.valueOf(m_price.group(0));
                        coin += Double.valueOf(m_count.group(0));
                    } else {
                        sumPrise -= Double.valueOf(m_price.group(0));
                        coin -= Double.valueOf(m_count.group(0));
                    }


                }

            }

            ResultModel resultModel = new ResultModel();
            avg = sumPrise / coin;
            resultModel.setNum(coin);
            resultModel.setPrice(avg);
            resultModel.setSum(sumPrise);
            return resultModel;


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }


    public static String unicode2String(String unicode) {
        StringBuffer string = new StringBuffer();
        String[] hex = unicode.split("\\\\u");
        for (int i = 1; i < hex.length; i++) {
            // 转换出每一个代码点
            int data = Integer.parseInt(hex[i], 16);
            // 追加成string
            string.append((char) data);
        }
        return string.toString();
    }
}
